package com.jiamao.goplay.ui.main;

import android.app.Application;
import android.util.Log;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.jiamao.goplay.bean.BaseRep;
import com.jiamao.goplay.bean.res.ResAddrDetail;
import com.jiamao.goplay.bean.res.ResCheckPhoto;
import com.jiamao.goplay.bean.res.ResUserInfoDetail;
import com.jiamao.goplay.config.Config;
import com.jiamao.goplay.data.BaseSubscriber;
import com.jiamao.goplay.data.DataRepository;
import com.jiamao.goplay.ui.discover.vm.AddrDetailVM;
import com.jiamao.goplay.ui.user.vm.UserPaifItemVM;
import com.jiamao.goplay.util.GsonUtil;
import com.kongzue.dialog.interfaces.OnDialogButtonClickListener;
import com.kongzue.dialog.util.BaseDialog;
import com.kongzue.dialog.util.DialogSettings;
import com.kongzue.dialog.v3.MessageDialog;
import com.netease.nim.uikit.business.uinfo.UserInfoHelper;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.RecentContact;
import com.tamsiree.rxkit.view.RxToast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.List;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.AppManager;
import me.goldze.mvvmhabit.base.BaseModel;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingConsumer;
import me.goldze.mvvmhabit.bus.Messenger;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.SPUtils;

public class MainViewModel extends BaseViewModel<DataRepository> {
    public MainViewModel(@NonNull Application application) {
        super(application);
    }

    public MainViewModel(@NonNull Application application, DataRepository model) {
        super(application, model);


        Messenger.getDefault().register(this, Config.MGER_PHOTO_MAIN,  String.class, new BindingConsumer<String>() {
            @Override
            public void call(String aMapLocation) {

                uc.pSwitchEvent.setValue("");
            }
        });


        Messenger.getDefault().register(this, "jiechu",  String.class, new BindingConsumer<String>() {
            @Override
            public void call(String aMapLocation) {

                KLog.d("aaaaaaaaaaaaaaaaaaaaaa  jiechu  String"+aMapLocation);
                showjiechuDialog(aMapLocation);


                //  uc.showJIechu.setValue(aMapLocation);
            }
        });
        Messenger.getDefault().register(this, "shanchu",  String.class, new BindingConsumer<String>() {
            @Override
            public void call(String aMapLocation) {
                KLog.d("aaaaaaaaaaaaaaaaaaaaaa  shanchu  "+aMapLocation);
              //  uc.pSwitchEvent.setValue("");
            }
        });


    }

    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();

    public class UIChangeObservable {
        //密码开关观察者
        public SingleLiveEvent<String> pSwitchEvent = new SingleLiveEvent<>();
        public SingleLiveEvent<Integer> refreshEvent = new SingleLiveEvent<>();
        public SingleLiveEvent<String> showJIechu = new SingleLiveEvent<>();

        public SingleLiveEvent<Integer> updateUICloectionStatus = new SingleLiveEvent<>();
        public SingleLiveEvent<String> startChat = new SingleLiveEvent<>();

    }

    public void getUserInfoDetail(){

        BaseSubscriber subscription = new BaseSubscriber<BaseRep<ResUserInfoDetail>>() {

            @Override
            public void onError(Throwable e) {
                super.onError(e);

            }

            @Override
            public void onComplete() {

            }

            @Override
            public void onNext(BaseRep<ResUserInfoDetail> baseRep) {
                super.onNext(baseRep);

                //保存账号密码
                if (baseRep.isOk()){

                    model.getmLocalDataSource().saveSex(baseRep.getData().getBaseInfo().getGender());
                    model.getmLocalDataSource().saveUserInfo(GsonUtil.toJson(baseRep.getData()));

                }else {
                 //    RxToast.showToastShort(baseRep.getMsg());
//
                }
            }
        };

        model.getApi().getMyUserInfo()
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
                .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                //    .doOnSubscribe(this) //请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {

                    }
                })
                .subscribe(subscription);



    }



    public void checkUserVlate(){

        BaseSubscriber subscription = new BaseSubscriber<BaseRep<ResCheckPhoto>>() {

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                checkUserVlate();

            }

            @Override
            public void onComplete() {

            }

            @Override
            public void onNext(BaseRep<ResCheckPhoto> baseRep) {
                super.onNext(baseRep);

                //保存账号密码
                if (baseRep.isOk()){

                    if (baseRep.getData().getStatus() == 1){
                       //uc.pSwitchEvent.setValue(1);
                    }else if (baseRep.getData().getStatus() == 0){
                        checkUserVlate();
                    }else{
                        uc.pSwitchEvent.setValue(baseRep.getData().getUrl());
                    }
                }else {

                    checkUserVlate();

                }
            }
        };

        model.getApi().checkavatarAuditStatus()
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
                .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                //    .doOnSubscribe(this) //请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {

                    }
                })
                .subscribe(subscription);



    }



    public void showjiechuDialog(String uid){


        String name = UserInfoHelper.getUserTitleName(uid, SessionTypeEnum.P2P);
        KLog.d("HTML","NAME:"+name+" uid:"+uid);
        MessageDialog.build((AppCompatActivity) AppManager.getAppManager().currentActivity())
                .setStyle(DialogSettings.STYLE.STYLE_IOS)
                .setTitle("你确定要和 "+name+" 解除配对关系吗?")
                .setMessage("")
                .setOkButton("确定", new OnDialogButtonClickListener() {
                    @Override
                    public boolean onClick(BaseDialog baseDialog, View v) {
                        model.getApi().relieveRelation(uid)
                                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                                .compose(RxUtils.schedulersTransformer())  // 线程调度
                                //   .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                                //    .doOnSubscribe(this) //请求与ViewModel周期同步
                                .doOnSubscribe(new Consumer<Disposable>() {
                                    @Override
                                    public void accept(Disposable disposable) throws Exception {
                                        //   uc.pSwitchEvent.setValue(1);
                                        showDialog();
                                        // dialog.show();
                                    }
                                })
                                .subscribe(new BaseSubscriber<BaseRep>() {
                                    @Override
                                    public void onNext(BaseRep baseRep) {

                                        super.onNext(baseRep);
                                        dismissDialog();
                                        if (baseRep.isOk()){

                                            Messenger.getDefault().send(uid,"shanchu");
                                         //   observableList.remove(vm);
                                            //  vm.updateypd();
                                        }else {
                                            RxToast.showToastShort(baseRep.getMsg());
                                        }
                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        dismissDialog();
                                        //   uc.pSwitchEvent.setValue(2);
                                        e.printStackTrace();
                                        RxToast.showToastShort("网络出现故障");
                                    }

                                    @Override
                                    public void onComplete() {
                                        //   dismissDialog();
                                    }

                                });
                        //AppApplication.getInstance().startLogins();
                        return false;
                    }

                }).setCancelButton("取消", new OnDialogButtonClickListener() {
            @Override
            public boolean onClick(BaseDialog baseDialog, View v) {

                //AppApplication.getInstance().startLogins();
                return false;
            }

        })
                .show();
    }

}
